import { callChromeMethod, initSandBoxEvents } from "./com"
interface ScriptInfo {
    info: ProjectItemWindow
    title: string
    code: string
}
const iframe = document.querySelector('iframe') as HTMLIFrameElement
const id = new URLSearchParams(location.search).get('id')
async function main() {

    if (!id) {
        console.log('no id')
        return
    }
    initSandBoxEvents()
    initEvents()


    if (!iframe) {
        console.log('no iframe')
        return
    }

    iframe.onload = () => {
        loadScript()
    }

}

async function loadScript() {
    const script = await callChromeMethod<ScriptInfo>('getScript', { id })
    document.title = script.title
    if (script.info || script.info) {
        const icoLink = document.querySelector('link[rel="shortcut icon"]') as HTMLLinkElement
        if (icoLink && script.info.icon) {
            icoLink.href = script.info.icon
        } else {
            const icon = document.createElement('link')
            icon.rel = 'shortcut icon'
            icon.type = 'image/x-icon'
            icon.href = script.info.icon||''
            document.head.appendChild(icon)
        }
    }
    iframe.contentWindow?.postMessage({ type: 'reload-script', data: script.code }, '*')
}

async function initEvents() {
    chrome.runtime.onMessage.addListener((message) => {
        const { type } = message
        if (type === 'side-panel-reload-script') {
            loadScript()
        }
    })
}

main().catch(console.error)